package com.qbw.app.module.user.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.view.Gravity;
import android.view.View;

import com.http.okhttp.HttpTask;
import com.lib.util.MatcherUtil;
import com.qbw.app.Constant;
import com.qbw.app.R;
import com.qbw.app.databinding.UserActivityResetPasswordBinding;
import com.qbw.app.model.Country;
import com.qbw.app.model.User;
import com.qbw.app.model.UserInfo;
import com.qbw.app.module.common.activity.CommonActivity;
import com.qbw.app.module.common.activity.SelectCountryAreaActivity;
import com.qbw.app.module.common.fragment.IKnowDialogFragment;
import com.qbw.app.module.common.util.CountryUtil;
import com.qbw.app.module.common.util.HttpRequestUtil;
import com.qbw.app.module.common.util.UniversalToastUtil;
import com.qbw.app.request.impl.CommonRequest;
import com.qbw.app.request.impl.UserRequest;
import com.qbw.core.observable.ObservableInt;
import com.qbw.core.observable.ObservableString;
import com.qbw.spm.P;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author QBW
 * @date 2019-09-21
 */
public class UserResetPasswordActivity extends CommonActivity<UserActivityResetPasswordBinding> implements IKnowDialogFragment.Listener {

    private final int REQUEST_CODE_SELECT_COUNTRY_AREA = 1;
    private Handler mHandler = new Handler();
    private Country mSelectedCountry;
    private ObservableString mCountryArea = new ObservableString();
    private ObservableString mPhone = new ObservableString();
    private ObservableString mPassword = new ObservableString();
    private ObservableString mVerifycode = new ObservableString();
    private ObservableString mError = new ObservableString();
    private ObservableInt mCountDown = new ObservableInt();

    private UserInfo mUserInfo;

    public static void startActivity(Context context, String telCodeTemp, String phoneTemp) {
        Intent intent = new Intent(context, UserResetPasswordActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra(Constant.KEY_TELCODE_TEMP, telCodeTemp);
        intent.putExtra(Constant.KEY_PHONE_TEMP, phoneTemp);
        context.startActivity(intent);

    }

    public static void startActivity(Context context, UserInfo userInfo) {
        Intent intent = new Intent(context, UserResetPasswordActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        intent.putExtra(Constant.KEY_USERINFO, userInfo);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.user_activity_reset_password;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = savedInstanceState == null ? getIntent().getExtras() : savedInstanceState;
        mUserInfo = (UserInfo) args.getSerializable(Constant.KEY_USERINFO);
        mBinding.title.setListener(this);
        mBinding.setCountryArea(mCountryArea);
        mBinding.setPhone(mPhone);
        mBinding.setPassword(mPassword);
        mBinding.setVerifycode(mVerifycode);
        mBinding.setError(mError);
        mBinding.setCountDownTime(mCountDown);
        mBinding.executePendingBindings();
        mBinding.tvGetVerifycode.setText(R.string.send);
        mBinding.tvCountryAreaValue.setOnClickListener(this);
        mBinding.tvGetVerifycode.setOnClickListener(this);
        mBinding.tvSure.setOnClickListener(this);
        mBinding.ivPasswordEye.setOnClickListener(this);

        Country.Response response = Country.Response.fromJson(P.getString(Constant.KEY_ALL_COUNTRYS));
        if (mUserInfo != null) {
            mCountryArea.setValue(mUserInfo.getTelCode());
            mPhone.setValue(mUserInfo.getPhone());
            mBinding.etPhonenumber.setEnabled(false);
            mSelectedCountry = response.getCountry(mCountryArea.getValue());
        } else {
            String telCode = args.getString(Constant.KEY_TELCODE_TEMP);
            if(TextUtils.isEmpty(telCode)) {
                telCode = P.getString(Constant.KEY_LAST_LOGIN_COUNTRY_AREA);
            }
            if (!TextUtils.isEmpty(telCode)) {
                mCountryArea.setValue(telCode);
                mSelectedCountry = response.getCountry(mCountryArea.getValue());
            } else {
                int cid = CountryUtil.getCountryId();
                mSelectedCountry = response.getCountry(cid);
                if (mSelectedCountry == null) {
                    if (response.size() > 0) {
                        mSelectedCountry = response.getData().get(0);
                        mCountryArea.setValue(mSelectedCountry.getTelCode());
                    }
                } else {
                    mCountryArea.setValue(mSelectedCountry.getTelCode());
                }
            }
            String phone = args.getString(Constant.KEY_PHONE_TEMP);
            if(TextUtils.isEmpty(phone)) {
                phone = P.getString(Constant.KEY_LAST_LOGIN_PHONE);
            }
            if (!TextUtils.isEmpty(phone)) {
                mPhone.setValue(phone);
            }
        }
    }

    @Override
    public void onClick(View v) {
        int vid = v.getId();
        if (vid == R.id.tv_sure) {
            if (checkInput(false)) {
                showLoadingDialog("");
                mGeneralManager.getRequestManager()
                               .getUserRequest()
                               .resetPassword(mCountryArea.getValue(),
                                              mPhone.getValue(),
                                              mPassword.getValue(),
                                              mVerifycode.getValue(),
                                              this)
                               .execute();
            }
        } else if (vid == R.id.tv_country_area_value) {
//            SelectCountryAreaActivity.startForResult(this, REQUEST_CODE_SELECT_COUNTRY_AREA);
        } else if (vid == R.id.tv_get_verifycode) {
            if (checkInput(true)) {
                mHandler.removeCallbacks(mCountDownTimeRunn);
                mCountDown.setValue(60);
                mHandler.post(mCountDownTimeRunn);
                mGeneralManager.getRequestManager()
                               .getCommonRequest()
                               .getVerifyCode(mCountryArea.getValue(),
                                              mPhone.getValue(),
                                              Constant.VERIFYCODE_TYPE_RESET_PASSWORD,
                                              this)
                               .execute();
                mBinding.etVerifycode.requestFocus();
            }
        } else if (vid == R.id.iv_password_eye) {
            if (mBinding.etPassword.getTransformationMethod() != null) {
                mBinding.etPassword.setTransformationMethod(null);
            } else {
                mBinding.etPassword.setTransformationMethod(new PasswordTransformationMethod());
            }
            if (mBinding.etPassword.getText().length() > 0) {
                mBinding.etPassword.setSelection(mBinding.etPassword.getText().length());
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_SELECT_COUNTRY_AREA) {
                Country country = (Country) data.getSerializableExtra(Constant.KEY_SELECTED_COUNTRY);
                mCountryArea.setValue(country.getTelCode());
                mSelectedCountry = country;
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable(Constant.KEY_USERINFO, mUserInfo);
    }

    private Runnable mCountDownTimeRunn = new Runnable() {
        @Override
        public void run() {
            int n = mCountDown.getValue() - 1;
            if (n > 0) {
                mHandler.postDelayed(mCountDownTimeRunn, 1000);
            }
            mCountDown.setValue(n);
        }
    };

    private boolean checkInput(boolean isGetVerifyCode) {
        if (mSelectedCountry == null) {
            UniversalToastUtil.showToast(R.string.please_select_country_area);
            return false;
        } /*else if (TextUtils.isEmpty(mPhone.getValue())) {
            UniversalToastUtil.showToast(R.string.input_phonenumber);
            return false;
        }*/
        if (!Pattern.compile(mSelectedCountry.getPhoneJs()).matcher(mPhone.getValue()).matches()) {
            UniversalToastUtil.showToast(R.string.invalid_phone_format);
            return false;
        }
        if (isGetVerifyCode) {
            return true;
        }
        if (TextUtils.isEmpty(mVerifycode.getValue())) {
            UniversalToastUtil.showToast(R.string.input_verify_code);
            return false;
        } else if (mPassword.getLength() < 6) {
            UniversalToastUtil.showToast(R.string.input_password);
            return false;
        }
        return true;
    }

    @Override
    public void onHttpSuccess(HttpTask httpTask, Object entity) {
        super.onHttpSuccess(httpTask, entity);
        String method = httpTask.getMethod();
        if (method.equals(UserRequest.METHOD_RESET_PASSWORD)) {
            IKnowDialogFragment.createInstance(gs(R.string.reset_password_success),
                                               Gravity.CENTER,
                                               "")
                               .show(getSupportFragmentManager(), "reset_password_success");
        }
    }

    @Override
    public void onHttpFailed(HttpTask httpTask, int errorCode, String message) {
        super.onHttpFailed(httpTask, errorCode, message);
        message = HttpRequestUtil.getMessage(errorCode, message);
        String method = httpTask.getMethod();
        if (method.equals(UserRequest.METHOD_RESET_PASSWORD)) {
            UniversalToastUtil.showFailedIconToast(message);
            closeLoadingDialog();
        } else if (method.equals(CommonRequest.METHOD_VERIFY_CODE)) {
            UniversalToastUtil.showFailedIconToast(message);
        }
    }

    @Override
    public void onIKnowDialogDismiss(int type) {
        finish();
    }
}
